import React, { useState, useEffect } from 'react';
import { Row, Col, Input, Select, Icon, message, Spin } from 'antd';
import FormItem from '../../../../components/FormItem';
import services from '../../../../services/api';
import { debounce } from 'lodash';
import './index.less';

const ReceiveUserItem = (props) => {
  const { value = {}, disabled, form, onDel, onAdd, isAddShow, isDelBtn, onNameChange } = props;
  const [nameOptions, setNameOptions] = useState([]);
  const [wxOptions, setWxOptions] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (value) {
      const label = value.user_id.label;
      const keyword = Array.isArray(label) ? label[0] : label;
      handleWxSearch(keyword);
    }
  }, [value.user_id.label]);

  // 搜索姓名
  const handleNameSearch = async (keyword) => {
    if (keyword) {
      setLoading(true);
      const { code, data, msg } = await services.dataReport.searchUser({ keyword });
      setLoading(false);
      if (code) return message.warning(msg);
      setNameOptions(data);
    } else {
      setNameOptions([]);
      setWxOptions([]);
    }
  };

  // 搜索企业微信
  const handleWxSearch = async (keyword) => {
    if (keyword) {
      const { code, data, msg } = await services.dataReport.searchWx({ keyword });
      if (code) message.warning(msg);
      setWxOptions(data);
    } else {
      setWxOptions([]);
    }
  };

  const checkUser = (_, value, callback) => {
    if (value && value.key) {
      return callback();
    }
    callback('请输入姓名');
  };

  const getFormItemList = () => {
    const { user_id, phone, email, wx_work, id } = value;
    return [
      {
        name: `users[${id}].user_id`,
        options: {
          initialValue: user_id || { key: '', label: '' },
          rules: [{ validator: checkUser }],
        },
        component: (
          <Select
            showSearch
            labelInValue
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={false}
            notFoundContent={loading ? <Spin size='small' /> : null}
            onSearch={debounce(handleNameSearch, 800)}
            onChange={(value) => onNameChange(value, nameOptions)}
          >
            {nameOptions.map((it) => {
              return (
                <Select.Option value={it.user_id} key={it.user_id}>
                  {it.user_name} <span style={{ color: '#999' }}>{it.dept_name}</span>
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      {
        name: `users[${id}].phone`,
        options: {
          initialValue: phone,
          rules: [{ pattern: /^\d{11}$/, message: '请输入正确的手机号' }],
        },
        component: <Input placeholder='手机号' />,
      },
      {
        name: `users[${id}].email`,
        options: {
          initialValue: email,
          rules: [{ type: 'email', message: '邮箱格式错误' }],
        },
        component: <Input placeholder='邮箱地址' />,
      },
      {
        name: `users[${id}].wx_work`,
        options: {
          initialValue: wx_work,
        },
        component: (
          <Select placeholder='企业微信' allowClear>
            {wxOptions &&
              wxOptions.map((it) => {
                return (
                  <Select.Option value={it.userId} key={it.userId}>
                    {it.name} <span style={{ color: '#999' }}>{it.position}</span>
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
    ];
  };
  return (
    <div className='item'>
      <Row type='flex' gutter={10} span={24}>
        {getFormItemList().map((item, index) => (
          <Col span={index === 2 ? 6 : 5} key={item.name}>
            <FormItem form={form} item={item} colNum={2} />
          </Col>
        ))}
        <Col span={3}>
          {!disabled && isDelBtn && <Icon type='minus-circle' className='op-btn' onClick={() => onDel && onDel()} />}
          {!disabled && isAddShow && <Icon type='plus-circle' className='op-btn' onClick={() => onAdd && onAdd()} />}
        </Col>
      </Row>
    </div>
  );
};

export default ReceiveUserItem;
